package com.example.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.reggie.common.PageInfo;
import com.example.reggie.common.R;
import com.example.reggie.entity.Category;
import com.example.reggie.service.CategoryServcie;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryServcie categoryServcie;
    @PostMapping("")
  public R<String> addCategory(@RequestBody Category category)
  {
      log.info("添加分类");
      boolean chk = categoryServcie.save(category);
      return  chk?R.success("添加成功"):R.error("添加失败");

   }
   @GetMapping("/page")
    public  R<Page> getCategory(PageInfo pageInfo)
   {
       LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
       queryWrapper.orderByAsc(Category::getSort);
       Page<Category> page = new Page<>(pageInfo.getPage(),pageInfo.getPageSize());
       categoryServcie.page(page,queryWrapper);
       return R.success(page);
   }

@DeleteMapping("")
    public  R<String> deleCategory(Long ids)
{
      log.info("删除分类："+ids);
    boolean chk = categoryServcie.remove(ids);
    return  chk?R.success("删除成功"):R.error("删除失败");
}
  @PutMapping("")
  public  R<String> updateCategory(@RequestBody Category category)
  {
      log.info("修改分类信息");
      categoryServcie.updateById(category);
      return  R.success("更新成功");
  }

  @GetMapping("/list")
    public  R<List<Category>>  queryCategeoryName(Category category)
  {
      LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
      queryWrapper.eq(category.getType()!=null,Category::getType,category.getType())
                    .orderByAsc(Category::getSort)
                  .orderByDesc(Category::getUpdateTime);
      List<Category> categoryList = categoryServcie.list(queryWrapper);
      return R.success(categoryList);
  }
}
